package com.jacky.ws.handler;

import com.jacky.ws.server.ChannelSupervise;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.handler.codec.http.websocketx.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.SimpleDateFormat;
import java.util.Date;

public class WebSocketTextFrameHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    private final Logger LOG = LoggerFactory.getLogger(WebSocketTextFrameHandler.class);
    private SimpleDateFormat sdf = new SimpleDateFormat("HHmmss");

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        LOG.info("服务端收到消息:{}", msg.text());
        String resp = sdf.format(new Date()) + ":" + msg.text();

        // 发送给所有客户端
        ChannelSupervise.send2All(new TextWebSocketFrame(resp));
        // 发送给当前客户端
        ctx.channel().writeAndFlush(new TextWebSocketFrame(resp));
    }

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("客户端加入连接:{}", ctx.channel().id());
        ChannelSupervise.addChannel(ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        LOG.info("客户端断开连接:{}", ctx.channel().id());
        ChannelSupervise.removeChannel(ctx.channel());
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        LOG.info("异常发生:{}", cause.getMessage());
        ctx.channel().close();
    }

}
